package com.snail.readyvr.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.snail.readyvr.R;
import com.snail.readyvr.adapter.CommonRecyclerAdapter;
import com.snail.readyvr.adapter.RecyclerViewHolder;
import com.snail.readyvr.application.MyApplication;
import com.snail.readyvr.di.component.DaggerLoginActivityPresenterComponent;
import com.snail.readyvr.di.module.LoginActivityPresenterModule;
import com.snail.readyvr.event.GetSessionEvent;
import com.snail.readyvr.event.LoginEvent;
import com.snail.readyvr.interfaces.MaxLengthWatcherListener;
import com.snail.readyvr.mvp.contract.LoginActivityContract;
import com.snail.readyvr.mvp.model.LoginParam;
import com.snail.readyvr.mvp.model.User;
import com.snail.readyvr.mvp.presenter.LoginActivityPresenter;
import com.snail.readyvr.rest.GetAccountInfoUtils;
import com.snail.readyvr.rest.RestApiUtils;
import com.snail.readyvr.ui.ClearEditText;
import com.snail.readyvr.ui.IndicatorTiTle;
import com.snail.readyvr.ui.ProgressButton;
import com.snail.readyvr.ui.ShowPassWordEditText;
import com.snail.readyvr.util.ApiException;
import com.snail.readyvr.util.AppUtils;
import com.snail.readyvr.util.Constant;
import com.snail.readyvr.util.EventBus;
import com.snail.readyvr.util.IntentParams;
import com.snail.readyvr.util.MD5Utils;
import com.snail.readyvr.util.MaxLengthWatcher;
import com.snail.readyvr.util.StartActivityUtils;
import com.snail.readyvr.util.StringUtils;
import com.snail.readyvr.util.TBSnackBarUtils;
import com.snail.readyvr.util.ToastUtils;
import com.snail.readyvr.util.Utils;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.OnClick;

public class LoginActivity extends BaseVRImageActivity implements MaxLengthWatcherListener , LoginActivityContract.View{

    @BindView(R.id.login_indicator)
    IndicatorTiTle mIndicatorTiTle;
    @BindArray(R.array.login_title)
    String[] mTitles;
    @BindView(R.id.login_username)
    ClearEditText mUserName;
    @BindView(R.id.login_psw)
    ShowPassWordEditText mPsw;
    @BindView(R.id.login_btn)
    ProgressButton mProgressButton;
    @BindView(R.id.forget_psw)
    TextView mForgetPsw;
    @BindView(R.id.register)
    TextView mRegister;

    @BindView(R.id.third_login_recycler)
    RecyclerView mRecyclerView;


    @BindView(R.id.login_activity_bg)
    LinearLayout mBgLayour;

    private boolean userNameOK = false;
    private boolean pswOK = false;

    private List<Integer> mThirdLoginRes;
    private CommonRecyclerAdapter<Integer> mAdapter;
    @Inject
    LoginActivityPresenter mPresenter;

    private int mFrom;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void init() {
        mFrom = getIntent().getIntExtra(IntentParams.LOGIN_FROM,0);
        initRes();
        mIndicatorTiTle.setTitls(mTitles);
        mProgressButton.setText(R.string.login);
        //mProgressButton.setShowProgress(true);
        mProgressButton.setEnabled(false);
        mForgetPsw.setText(Utils.getUnderLineText(getString(R.string.forget_psw)));
        mRegister.setText(Utils.getUnderLineText(getString(R.string.register)));
        MaxLengthWatcher userNameWatcher = new MaxLengthWatcher(50, mUserName);
        userNameWatcher.setMaxLengthWatcherListener(this);
        mUserName.setTextWatcher(userNameWatcher);
        mUserName.setActivated(false);
        if(getIntent().hasExtra(IntentParams.LOGIN_USERNAME)){
            mUserName.setText(getIntent().getStringExtra(IntentParams.LOGIN_USERNAME));
        }
        MaxLengthWatcher pswWatcher = new MaxLengthWatcher(50, mPsw);
        pswWatcher.setMaxLengthWatcherListener(this);
        mPsw.setTextWatcher(pswWatcher);
        mPsw.setActivated(false);
        mAdapter = new CommonRecyclerAdapter<Integer>(this,R.layout.third_login_item_layout) {
            @Override
            public void bindData(RecyclerViewHolder holder, int position, Integer item) {
              holder.setImageResource(R.id.third_login_img,item)
                      .setOnClickListener(R.id.third_login_img, new View.OnClickListener() {
                          @Override
                          public void onClick(View v) {
                          ToastUtils.show(LoginActivity.this,R.string.no_third_login_tip);
                          }
                      });
            }
        };
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.clearAndAddList(mThirdLoginRes);
        DaggerLoginActivityPresenterComponent.builder().applicationComponent(((MyApplication)getApplication()).getApplicationComponent())
                .loginActivityPresenterModule(new LoginActivityPresenterModule(this))
                .build().inject(this);
        mPresenter.start();
    }


    private void initRes() {
        mThirdLoginRes = new ArrayList<>();
        mThirdLoginRes.add(R.drawable.login_facebook_bg_selector);
        mThirdLoginRes.add(R.drawable.login_line_bg_selector);
        mThirdLoginRes.add(R.drawable.login_tumblr_bg_selector);
        mThirdLoginRes.add(R.drawable.login_google_bg_selector);
        mThirdLoginRes.add(R.drawable.login_twitter_bg_selector);
        mThirdLoginRes.add(R.drawable.login_wechat_bg_selector);
        mThirdLoginRes.add(R.drawable.login_qq_bg_selector);
        mThirdLoginRes.add(R.drawable.login_weibo_bg_selector);

    }

    @OnClick(R.id.login_btn)
    public void onClickLoginBtn() {
        if(Utils.checkNetWork(this)){
            changeState(true);
            if(!StringUtils.isNull(Utils.sessionid)) {
                askLogin(false);
            }
            else
                mPresenter.getSessionId(GetSessionEvent.FROM_LOGIN);
        }
    }

    public void changeState(boolean loading){
        mUserName.clearFocus();
        mUserName.setActivated(false);
        mUserName.setEnabled(!loading);
        mPsw.clearFocus();
        mPsw.setActivated(false);
        mPsw.setEnabled(!loading);
        mProgressButton.setText(loading?R.string.logining:R.string.login);
        mProgressButton.setShowProgress(loading);
        if(!loading)
            changeLoginBtn();
        else
            mProgressButton.setEnabled(false);
    }

    public void askLogin(boolean isVistor){
        LoginParam param = new LoginParam();
        param.setDevid(AppUtils.getWIFIMac(MyApplication.getmContext()));
        if (isVistor) {
            Utils.sUser = new User();
            param.setUsername("guest");
            mPresenter.login(LoginEvent.FROM_VISTOR_LOGIN, param);
        } else {
            param.setType(Constant.REGISTER_PSW_TYPE);
            param.setPassword(MD5Utils.getMD5_16(mPsw.getText().toString().trim()));
            param.setUsername(mUserName.getText().toString().trim());
            mPresenter.login(mFrom, param);
        }

    }

    @OnClick(R.id.forget_psw)
    public void onClickForgetPsw() {
        StartActivityUtils.startRegisterActivity(LoginActivity.this, Constant.FROM_FIND_PSW);
    }

    @OnClick(R.id.register)
    public void onClickRegister() {
        StartActivityUtils.startRegisterActivity(LoginActivity.this, Constant.FROM_REGISTER);
        finish();
    }

    @OnClick(R.id.visitor_login)
    public void onClickVistor(){
        if(Utils.checkNetWork(this)){
            if(!StringUtils.isNull(Utils.sessionid))
                askLogin(true);
            else
            mPresenter.getSessionId(GetSessionEvent.FROM_VISTOR_LOGIN);
        }
    }

    @Override
    public void overMaxLength(View view, int max) {

    }

    @Override
    public void lengthChanged(View view, int length) {
        switch (view.getId()) {
            case R.id.login_username:
                if (length > 0 && (Utils.isEmail(mUserName.getText().toString()) || Utils.isMobileNum(mUserName.getText().toString()))) {
                    userNameOK = true;
                } else {
                    userNameOK = false;
                }
                break;
            case R.id.login_psw:
                if (length > 0 && Utils.checkPsw(mPsw.getText().toString().trim())) {
                    pswOK = true;
                } else {
                    pswOK = false;
                }
                break;
        }
        changeLoginBtn();
    }

    private void changeLoginBtn() {
        if (userNameOK && pswOK) {
            if (!mProgressButton.isEnabled())
                mProgressButton.setEnabled(true);
        } else {
            if (mProgressButton.isEnabled())
                mProgressButton.setEnabled(false);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mUserName.setText(null);
        mPsw.setText(null);
        mFrom = intent.getIntExtra(IntentParams.LOGIN_FROM,0);
        if(intent.hasExtra(IntentParams.LOGIN_USERNAME)){
            mUserName.setText(intent.getStringExtra(IntentParams.LOGIN_USERNAME));
        }
    }

    /*@Override
    public void getTokenSuceess(GetTokenResponse response) {
        if(response != null && response.getToken() != null){
            Utils.token = response.getToken();
            LogUtils.d(Utils.token);
            //跳转播放页面页面
            *//*Intent intent = new Intent(LoginActivity.this, PlayActivity.class);
            LoginActivity.this.startActivity(intent);*//*
            StartActivityUtils.startVideoPlayActivity(this);
            finish();
        }else {
            TBSnackBarUtils.showShort(this,R.string.get_token_error_tip);
        }

    }*/

   /* @Override
    public void getTokenFaile(Throwable e) {

        TBSnackBarUtils.showShort(this,e.getMessage() + "");

    }*/

    @Override
    public void showProgress() {

    }

    @Override
    public void dismissProgress() {

    }

    @Override
    public void error(Throwable throwable) {

    }

    @Override
    public void loginSuccess() {

    }

    @Override
    protected void hasGetAllPermissions() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(thread = EventThread.MAIN_THREAD, tags = {@Tag(Constant.BusTag.GET_SESSIONID_TAG)})
    public void onGetDessionId(GetSessionEvent getSessionEvent){
      if(getSessionEvent != null){
          if(getSessionEvent.getType() == GetSessionEvent.TYPE_FAILE){
              TBSnackBarUtils.showShort(this,R.string.get_sessionid_error_tip);
              if(getSessionEvent.getFrom() == GetSessionEvent.FROM_LOGIN){
                  changeState(false);
              }
          }else if (getSessionEvent.getType() == GetSessionEvent.TYPE_SUCCESS ){
              if(getSessionEvent.getFrom() == GetSessionEvent.FROM_VISTOR_LOGIN)
                  askLogin(true);
              else if(getSessionEvent.getFrom() == GetSessionEvent.FROM_LOGIN)
                  askLogin(false);
          }
      }
    }

    @Subscribe(thread = EventThread.MAIN_THREAD, tags = {@Tag(Constant.BusTag.LOGIN_TAG)})
    public void onLoginFinish(LoginEvent event){
        if (event != null) {
            if (event.getType() == LoginEvent.TYPE_FAILE) {
                changeState(false);
                if (event.getThrowable() != null){
                    if (event.getThrowable() instanceof ApiException) {
                        ApiException apiException = (ApiException) event.getThrowable();
                        TBSnackBarUtils.showShort(this, Utils.getErrorTip(apiException.getCode()) + "");
                        if(apiException.getWhichApi() == RestApiUtils.LOGIN_API){
                            if(apiException.getCode() == 3013){
                                mUserName.setActivated(true);
                                mPsw.setActivated(true);
                            }
                        }
                    } else {
                        TBSnackBarUtils.showShort(this, event.getThrowable().getMessage() + "");
                    }
                }else {
                    loginfailed();
                }
            } else if (event.getType() == LoginEvent.TYPE_SUCCESS ){
                GetAccountInfoUtils.getAccountInfo(((MyApplication)getApplication()).getApplicationComponent().getLoginRestClient());
                if(event.getFrom() != LoginEvent.FROM_VISTOR_LOGIN)
                     ToastUtils.show(this, R.string.login_success);
                if (event.getFrom() == LoginEvent.FROM_LOGIN || event.getFrom() == LoginEvent.FROM_VISTOR_LOGIN) {

                    StartActivityUtils.startVideoPlayActivity(this);
                    //StartActivityUtils.startSelectChannelActivity(this);
                }
                finish();
            }
        } else {
            ToastUtils.show(this, R.string.login_failed);
            changeState(false);
        }


    }

    private void loginfailed() {
        ToastUtils.show(this, R.string.login_failed);
        int i = Display.DEFAULT_DISPLAY;
        changeState(false);
    }


}
